package ysq.xyg.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.recovery.model.po.RecoveryRecord;
import ysq.xyg.recovery.service.PowerMemberService;
import ysq.xyg.recovery.service.RecoveryRecordService;
import ysq.xyg.shop.dao.ShopWithdrawDao;
import ysq.xyg.shop.model.po.ShopWithdraw;
import ysq.xyg.shop.model.vo.ShopWithdrawVo;
import ysq.xyg.shop.service.ShopWithdrawService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.wxapi.api.WxApiClient;
import ysq.xyg.wxapi.model.base.TemplateMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 商城模块-提现表service实现
 *
 * @author congcong tao
 * @date 2019-4-28 11:19:58
 */
@Service("shopWithdrawService")
public class ShopWithdrawServiceImpl extends BaseServiceImpl<ShopWithdraw> implements ShopWithdrawService {

    @Autowired
    private PowerMemberService powerMemberService;
    @Autowired
    private WebMemberService webMemberService;
    @Autowired
    private RecoveryRecordService recoveryRecordService;
    @Resource
    private ShopWithdrawDao shopWithdrawDao;

    private ShopWithdraw shopWithdraw;

    @Autowired
    public void setBaseDao(ShopWithdrawDao shopWithdrawDao) {
        this.baseDao = shopWithdrawDao;
    }

    /**
     * 分页查询
     *
     * @param shopWithdrawVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity page(ShopWithdrawVo shopWithdrawVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<ShopWithdraw> list = acceptList(shopWithdrawVo);
        PageInfo<ShopWithdraw> page=new PageInfo<ShopWithdraw>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(ShopWithdrawVo shopWithdrawVo, int pageSize, int pageNum) {
        if (StringUtils.isNotEmpty(shopWithdrawVo.getMemberNickName())) {
            shopWithdrawVo.setMemberNickName(BaseUtil.encodeBase64String(shopWithdrawVo.getMemberNickName()));
        }
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<ShopWithdraw> list = shopWithdrawDao.selectEntityList(shopWithdrawVo);
        // nickName
        if (list != null && list.size() > 0) {
            for (ShopWithdraw shopWithdraw : list) {
                if (StringUtil.isNotEmpty(shopWithdraw.getMemberNickName())) {
                    shopWithdraw.setMemberNickName(BaseUtil.decodeBase64(shopWithdraw.getMemberNickName()));
                }
                if (shopWithdraw.getCreateTime() != null) {
                    shopWithdraw.setCreateTimeStr(DateUtil.formatDateTime(shopWithdraw.getCreateTime()));
                }
            }
        }
        PageInfo<ShopWithdraw> page=new PageInfo<ShopWithdraw>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param shopWithdrawVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity addOrUpdate(ShopWithdrawVo shopWithdrawVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(shopWithdrawVo.getId())){
            shopWithdraw=new ShopWithdraw(currentUser);
            isUpate=false;
        }else{
            shopWithdraw=selectByPrimaryKey(shopWithdrawVo.getId());
            if(ObjectUtil.isNull(shopWithdraw)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            shopWithdraw.setUpdateTime(new Date());
            shopWithdraw.setUpdateUser(currentUser.getId());
        }
        shopWithdraw.setMemberId(shopWithdrawVo.getMemberId());
        shopWithdraw.setMoney(shopWithdrawVo.getMoney());
        shopWithdraw.setAlipay(shopWithdrawVo.getAlipay());
        shopWithdraw.setBankCard(shopWithdrawVo.getBankCard());
        shopWithdraw.setStatus(shopWithdrawVo.getStatus());
        shopWithdraw.setManageStatus(shopWithdrawVo.getManageStatus());
        shopWithdraw.setDescription(shopWithdrawVo.getDescription());
        shopWithdraw.setApplyTime(shopWithdrawVo.getApplyTime());
        shopWithdraw.setManageTime(shopWithdrawVo.getManageTime());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(shopWithdraw);
        }else{
            num=insert(shopWithdraw);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }
    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        ShopWithdraw shopWithdraw=selectByPrimaryKey(id);
        if(shopWithdraw!=null){
            shopWithdraw.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            shopWithdraw.setUpdateTime(new Date());
            shopWithdraw.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(shopWithdraw);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param shopWithdrawVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public List<ShopWithdraw> acceptList(ShopWithdrawVo shopWithdrawVo){
        Example example = new Example(ShopWithdraw.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(shopWithdrawVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",shopWithdrawVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return shopWithdrawDao.selectByExample(example);
    }

    @Override
    public List<ShopWithdraw> selectEntityList(ShopWithdrawVo shopWithdrawVo) {
        return shopWithdrawDao.selectEntityList(shopWithdrawVo);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity withdrawEdit(WebMember webMember, String status, String money) {
        if (Integer.parseInt(money) > webMember.getScore()) {
            return new ReturnEntity(BaseConstant.FAIL, "您拥有的积分不够");
        }
        String id = BaseUtil.uId();
        ShopWithdraw withdraw = new ShopWithdraw();
        withdraw.setId(id);
        withdraw.setMemberId(webMember.getId());
        // money就是积分
        withdraw.setMoney(money);
        withdraw.setStatus(status);
        withdraw.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        withdraw.setCreateTime(new Date());
        int flag = this.insert(withdraw);
        if(flag <= 0){
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        // 需要修改自身金额
        if (webMember != null && StringUtils.isNotEmpty(money)) {
            // 减去积分
            String nickName = webMember.getNickName();
            // 需要计算总金额，并提交到webMember中
            webMember.setNickName(null);
            webMember.setScore(webMember.getScore() - Integer.parseInt(money));
            webMemberService.updateByPrimaryKeySelective(webMember);
            // 积分记录表
            RecoveryRecord recoveryRecord = new RecoveryRecord();
            recoveryRecord.setId(BaseUtil.uId());
            recoveryRecord.setMemberId(webMember.getId());
            recoveryRecord.setMoney(money);
            recoveryRecord.setDescription(String.format("提现减去%s积分", money));
            recoveryRecord.setCreateTime(DateUtil.date());
            recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
            recoveryRecord.setType(BaseConstant.RECORD_STATUS_CUT_SCORE);
            recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            recoveryRecordService.insert(recoveryRecord);
            // 提现提醒
            String openId = powerMemberService.selectOpenIdByType(BaseConstant.POWER_MEMBER_WITHDRAW);
            TemplateMessage templateMessage=new TemplateMessage();
            templateMessage.setUrl("");
            templateMessage.setOpenid(openId);
            templateMessage.setTemplateId("ouGM0xpEXP4VBp-ePNa06b_PRyCgG_H3QeMI_iNtez0");
            Map<String,String> data=new HashMap<String, String>();
            data.put("first", "您有一个用户提现");
            data.put("keyword1", nickName);
            data.put("keyword2", DateUtil.formatDateTime(DateUtil.date()));
            // 积分和元的兑换
            data.put("keyword3", money + "积分");
            data.put("keyword4", "微信");
            data.put("remark", "备注：请尽快查处理");
            templateMessage.setDataMap(data);
            WxApiClient.sendTempletNotice(templateMessage);
            return new ReturnEntity();
            /*Double memberMoney = webMember.getMoney();
            Double moneyD = Double.parseDouble(money);
            if (memberMoney < moneyD) {
                this.deleteByPrimaryKey(id);
                return new ReturnEntity(BaseConstant.FAIL, "您的剩余金额不足");
            }
            // 避免解析后的nickname传过去
            webMember.setNickName(null);
            webMember.setMoney(memberMoney - moneyD);
            webMemberService.updateByPrimaryKeySelective(webMember);*/
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateStatus(String id, String status, String description) {
        if(StringUtil.isEmpty(id)){
            return new ReturnEntity(BaseConstant.FAIL, "ID为空");
        }
        ShopWithdraw withdraw = this.selectByPrimaryKey(id);
        withdraw.setStatus(status);
        withdraw.setDescription(description);
        int info = this.updateByPrimaryKey(withdraw);
        if (info <= 0) {
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        if (StringUtils.equals(status, BaseConstant.RECOVERY_WASTE_MEMBER_STATUS_THREE)) {
            // 如果是驳回，需要将积分还给用户
            if (StringUtils.isNotEmpty(withdraw.getMoney())) {
                WebMember webMember = webMemberService.selectByPrimaryKey(withdraw.getMemberId());
                webMember.setScore(webMember.getScore() + Integer.parseInt(withdraw.getMoney()));
                int num = webMemberService.updateByPrimaryKey(webMember);
                // 增加积分记录
                // 积分记录表
                RecoveryRecord recoveryRecord = new RecoveryRecord();
                recoveryRecord.setId(BaseUtil.uId());
                recoveryRecord.setMemberId(webMember.getId());
                recoveryRecord.setMoney(withdraw.getMoney());
                recoveryRecord.setDescription(String.format("提现失败回退%s积分", withdraw.getMoney()));
                recoveryRecord.setCreateTime(DateUtil.date());
                recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
                recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
                recoveryRecord.setType(BaseConstant.RECORD_STATUS_ADD_SCORE);
                recoveryRecordService.insert(recoveryRecord);

                if (num <= 0) {
                    return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
                }
            }
        }
        return new ReturnEntity();
    }
}
